package com.example.carefree_server.controller.c_studentController;

import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/student")
public class ExcelExportController {

    @PostMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response, @RequestBody List<List<String>> data) throws IOException {
        // 设置响应头，以便浏览器下载文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=activity_" + System.currentTimeMillis() + ".xlsx");

        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("活动数据表");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        String[] titles = {"活动名称", "活动负责部门/社团", "学号", "姓名", "活动主类型", "活动副类型", "参与日期", "参与证明"};
        for (int i = 0; i < titles.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(titles[i]);
        }

        // 填充数据
        for (int i = 0; i < data.size(); i++) {
            Row row = sheet.createRow(i + 1);
            List<String> rowData = data.get(i);
            for (int j = 0; j < rowData.size(); j++) {
                row.createCell(j).setCellValue(rowData.get(j));
            }
        }

        // 写入到响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }
}
